package com.c5p1ng.route.filter;

import com.c5p1ng.route.context.GlobalContext;
import com.c5p1ng.route.util.ContextUtil;
import com.c5p1ng.route.util.SpringContextUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang.StringUtils;
import org.slf4j.MDC;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;

import java.util.UUID;

/**
 * 上下文透传filter 辅助类
 *
 * @author csp
 */
public class HeaderContentFilterHelper {

    static boolean isInitTraceId = true;

    public static void setIsInitTraceId(boolean isInit){
        isInitTraceId  = isInit;
    }
    public static void initGlobalContext(String contextStr, String clientIp) {
        GlobalContext globalContext;
        if (StringUtils.isEmpty(contextStr)) {
            globalContext = new GlobalContext();
        } else {
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                globalContext = objectMapper.readValue(contextStr, GlobalContext.class);
            } catch (Exception e) {
                globalContext = new GlobalContext();
            }
        }
        if (StringUtils.isEmpty(globalContext.getClientIp())) {
            globalContext.setClientIp(clientIp);
        }

        if (StringUtils.isEmpty(globalContext.getGroup())) {
            ApplicationContext context = SpringContextUtil.getContext();
            if(context != null) {
                Environment env = context.getEnvironment();
                globalContext.setGroup(env.getProperty("spring.cloud.nacos.discovery.group", "DEFAULT_GROUP"));
            } else {
                globalContext.setGroup("DEFAULT_GROUP");
            }
        }

        ContextUtil.setCurrentContext(globalContext);
        if(StringUtils.isEmpty(globalContext.getTraceId())) {
            String traceId = MDC.get(ContextUtil.TRACE_ID);
            if(traceId == null && isInitTraceId) {
                traceId = UUID.randomUUID().toString();
            }
            ContextUtil.setTranceId(traceId);
        }
    }

}
